package peng.yang.express.Fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.sortlistview.CharacterParser;
import com.sortlistview.ClearEditText;
import com.sortlistview.PinyinComparator;
import com.sortlistview.SideBar;
import com.sortlistview.SortAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import peng.yang.express.Bean.PhoneMembers;
import peng.yang.express.Bean.SortModel;
import peng.yang.express.R;
import peng.yang.express.Util.PhoneMembersDao;

/**
 * Created by Administrator on 2016/6/24.
 */
public class Fragment03 extends Fragment {

    private View rootView;

    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;
    private String TAG = "Fragment03";


    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;


    private RequestQueue requestQueue;
    private List<SortModel> SourceDateList;


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_03, null);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        sortListView = (ListView) rootView.findViewById(R.id.country_lvcountry);

        initData();

        return rootView;

    }

    private void initData() {
        PhoneMembersDao dao = new PhoneMembersDao(getContext());
        List<PhoneMembers> memberses = dao.getAllMembers();
        SourceDateList = new ArrayList<SortModel>();
        Log.e(TAG + "memberses.size()", memberses.size() + "");
        for (int i = 0; i < memberses.size(); i++) {
            SortModel sortModel = new SortModel();
            sortModel.setImageId(memberses.get(i).getNetImageUrl().toString());

            sortModel.setFileImagePath(memberses.get(i).getFileImagePath().toString());
            sortModel.setNum(memberses.get(i).getPhone().toString());
            sortModel.setName(memberses.get(i).getExpName().toString());
            sortModel.setSigleName(memberses.get(i).getSimpleName().toString());
            //汉字转换成拼音
            String pinyin = CharacterParser.converCnToPY(sortModel.getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            SourceDateList.add(sortModel);
        }
        Log.e(TAG + "SourceDateList", SourceDateList.get(0).toString());


        adapter = new SortAdapter(getContext(), SourceDateList);
        sortListView.setAdapter(adapter);
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String num =SourceDateList.get(position).getNum();
                Uri uri = Uri.parse("tel:"+num);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_CALL);
                intent.setData(uri);
                startActivity(intent);
            }
        });

        initViews();

    }
    private void initViews() {
        //实例化汉字转拼音类

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) rootView.findViewById(R.id.sidrbar);
        dialog = (TextView) rootView.findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });

/*
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                //这里要利用adapter.getItem(position)来获取当前position所对应的对象
                Toast.makeText(getContext(), ((SortModel) adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
            }
        });*/

        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortAdapter(getContext(), SourceDateList);
        sortListView.setAdapter(adapter);


        mClearEditText = (ClearEditText) rootView.findViewById(R.id.filter_edit);

        //根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

/*
    *//**
     * 为ListView填充数据
     * @param date
     * @return
     *//*
    private List<SortModel> filledData(String [] date){
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for(int i=0; i<date.length; i++){
            SortModel sortModel = new SortModel();
            sortModel.setName(date[i]);
            //汉字转换成拼音
            String pinyin = CharacterParser.converCnToPY(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if(sortString.matches("[A-Z]")){
                sortModel.setSortLetters(sortString.toUpperCase());
            }else{
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }*/


    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : SourceDateList) {
                String name = sortModel.getName();
                name = name.toUpperCase();
                String pname = CharacterParser.converCnToPY(name).toUpperCase();
                if (name.indexOf(filterStr.toString().toUpperCase()) != -1 || pname.startsWith(filterStr.toString().toUpperCase())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }


}

